//
//  XYComposeView.swift
//  SinaWB_XY
//
//  Created by 小熊猫 on 15/10/20.
//  Copyright © 2015年 小熊猫. All rights reserved.
//

import UIKit
import pop




class XYComposeView: UIView {
    
    //装按钮的数组
    var buttonArray:[XYComposeButton] = [XYComposeButton]()
    
    //需要添加view的控制器
    var showVC: UIViewController?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
//        self.backgroundColor = UIColor.redColor()
        
        self.frame = CGRectMake(0, 0, SCREENW, SCREENH)
//        //添加背景图片
        let backImage = UIImageView(image: self.setBackgroundImage().applyLightEffect())
        backImage.size = self.size
        self.addSubview(backImage)
        
        //添加按钮
        addSubButton()
        
        //添加图标
        addSubview(logImage)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //截取当前屏幕的图片
    private func setBackgroundImage() -> UIImage{
        
        //获取当前屏幕
        let window = UIApplication.sharedApplication().keyWindow
        
        //开启上下文
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(SCREENW, SCREENH), false, 1)
        
        window?.drawViewHierarchyInRect(window!.bounds, afterScreenUpdates: true)
        //从上下文中获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        //关闭上下文
        UIGraphicsEndImageContext()
        
        return image
    }
    
    //添加按钮
    private func  addSubButton(){
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)
        
        let array = NSArray(contentsOfFile: path!)
        
        //计算间距
        let margin = (SCREENW - 3 * BUTTON_W) / 4
        
        //遍历数组中的字典
        for i in 0..<array!.count{
            //创建button
            let button = XYComposeButton()
            
            //将数组中的字典信息取出来
            let dict = array![i] as! [String:AnyObject]
            
            button.setImage(UIImage(named: (dict["icon"] as! String)), forState: UIControlState.Normal)
            button.setTitle((dict["title"] as! String), forState: UIControlState.Normal)
            
            //添加点击事件
            button.addTarget(self, action: "didClickButton:", forControlEvents: UIControlEvents.TouchUpInside)
            
            //设置x和y
            let row = i / 3
            let col = i % 3
            
            button.x = CGFloat(col) * BUTTON_W + CGFloat(col + 1) * margin
            button.y = CGFloat(row) * BUTTON_H + SCREENH
            
            self.addSubview(button)
            buttonArray.append(button)
        }
        
    }
    
    //按钮的点击事件,让图片变大
    @objc private func didClickButton(seleButton:XYComposeButton){
        
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            for value in self.buttonArray{
                if value == seleButton{
                    value.transform = CGAffineTransformMakeScale(2, 2)
                }else{
                    value.transform = CGAffineTransformMakeScale(0.5, 0.5)
                }
                value.alpha = 0.0
            }
            }) { (finish) -> Void in
                
                
                let composeTextVc = XYComposeTextController()
                self.showVC?.presentViewController(XYNavVC(rootViewController: composeTextVc), animated: true, completion: { () -> Void in
                    self.removeFromSuperview()
                })                
        }
        
    }
    
    
    //懒加载一个log图片
    private lazy var logImage:UIImageView = {
    
        let imageView = UIImageView(image: UIImage(named: "compose_slogan"))
        imageView.centerX = SCREENW * 0.5
        imageView.centerY = 100
        
        return imageView
    }()
    
    //显示界面
    func show(showViewVC:UIViewController){
        showViewVC.view.addSubview(self)
        
        self.showVC = showViewVC
        //这个时候要添加动画
        
        for (index,value) in self.buttonArray.enumerate(){
             self.anim(value,valueX:value.centerX, valueY: value.centerY - 400, index: index)
        }
    }
    
    //移除界面
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        dismiss()
    }
    
    private func dismiss(){
        
        for (index,value) in self.buttonArray.reverse().enumerate(){
            self.anim(value,valueX:value.centerX, valueY: value.centerY + 400, index: index)
        }
        

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.removeFromSuperview()
        }
    }
    
    //执行的动画
    private func anim(value:XYComposeButton,valueX:CGFloat,valueY:CGFloat,index:Int){
        
        //创建一个弹性动画
        let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        //执行到什么位置
        anim.toValue = NSValue(CGPoint: CGPointMake(valueX, valueY))
        //弹性幅度
        anim.springBounciness = 10
        //速度
        anim.springSpeed = 10
        //延迟事件
        anim.beginTime = CACurrentMediaTime() + Double(index) * 0.025
        value.pop_addAnimation(anim, forKey: nil)
    }
}





